package com.ruoyi.waybill.controller;

import java.util.List;
import javax.servlet.http.HttpServletResponse;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.pack.PackUtils;
import com.ruoyi.goods.service.ITGoodsInfoService;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.waybill.domain.TWayBillInfo;
import com.ruoyi.waybill.service.ITWayBillInfoService;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.system.domain.TSendReceiveInfo;
import com.ruoyi.system.service.ITSendReceiveInfoService;
import com.ruoyi.system.domain.TVehicleDriverInfo;
import com.ruoyi.system.service.ITVehicleDriverInfoService;
import com.ruoyi.common.utils.order.OrderUtils;
import com.ruoyi.common.utils.snowflake.SnowFlake;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * 运单信息Controller
 * 
 * @author ruoyi
 * @date 2023-12-09
 */
@RestController
@RequestMapping("/waybills/waybill")
public class TWayBillInfoController extends BaseController
{
    @Autowired
    private ITWayBillInfoService tWayBillInfoService;

    @Autowired
    private ITSendReceiveInfoService tSendReceiveInfoService;

    @Autowired
    private ITVehicleDriverInfoService tVehicleDriverInfoService;

    @Autowired
    private ITGoodsInfoService tGoodsInfoService;

    //@Autowired
    //private TSendReceiveInfo tSendReceiveInfo = new TSendReceiveInfo();

    //private TVehicleDriverInfo tVehicleDriverInfo = new TVehicleDriverInfo();

    private static Logger logger = LoggerFactory.getLogger(TWayBillInfoController.class);

    /**
     * 查询运单信息列表
     */
    @PreAuthorize("@ss.hasPermi('waybills:waybill:list')")
    @GetMapping("/list")
    public TableDataInfo list(TWayBillInfo tWayBillInfo)
    {
        String bundleNumber = tWayBillInfo.getBundleNumber();
        StringBuilder slqBundleNumber = new StringBuilder();
//        logger.debug("GGG " + "tWayBillInfo = " + tWayBillInfo.getBundleNumber());
        if(!(bundleNumber == null || bundleNumber.isEmpty())) {
            //String[] split = bundleNumber.split(",");
            for (String item : bundleNumber.split(",")) {
                slqBundleNumber.append(',');
                slqBundleNumber.append('\'' + item + '\'');
            }
            tWayBillInfo.setBundleNumber(slqBundleNumber.substring(1));
//            logger.debug("XXX " + "tWayBillInfo = " + tWayBillInfo.getBundleNumber());
        }

        //logger.debug("GGG " + "getLoginUser().getUser().getCustoms() = " + getLoginUser().getUser().getCustoms());
        //List<String> customs = getLoginUser().getUser().getCustoms();
        //logger.debug("GGG " + "customs.toString() = " + customs.toString());
        //logger.debug("GGG " + "customs.size() = " + customs.size());
        //tWayBillInfo.setSendGoodsCustomer(customs.toString());
        //tWayBillInfo.setSendGoodsCustomer(customs.get(0));
        //tWayBillInfo.setSendGoodsCustomer("环宇顺诚(北京)信息科技有限公司,天津盛鑫达运输有限公司");
        //logger.debug("GGG X" + "tWayBillInfo = " + tWayBillInfo);
//        logger.debug("GGG IN " + "OrderUtils.getOrderNumber = " + OrderUtils.getOrderNumber("IN", "-"));
        //SnowFlake snowFlake = new SnowFlake(3, 16);
        //logger.debug("GGG IN " + "SnowFlake = " + snowFlake.nextId());
        //long id = snowFlake.nextId();
        //long[] arr = snowFlake.parseId(id);
        //System.out.println(snowFlake.formatId(id));
//        logger.debug("GGG NL" + "PackUtils.getPackNumber = " + PackUtils.getPackNumber("NL", "", 12));

        startPage();
        List<TWayBillInfo> list = tWayBillInfoService.selectTWayBillInfoList(tWayBillInfo);
        return getDataTable(list);
    }

    /**
     * 导出运单信息列表
     */
    @PreAuthorize("@ss.hasPermi('waybills:waybill:export')")
    @Log(title = "运单信息", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, TWayBillInfo tWayBillInfo)
    {
        List<TWayBillInfo> list = tWayBillInfoService.selectTWayBillInfoList(tWayBillInfo);
        ExcelUtil<TWayBillInfo> util = new ExcelUtil<TWayBillInfo>(TWayBillInfo.class);
        util.exportExcel(response, list, "运单信息数据");
    }

    /**
     * 获取运单信息详细信息
     */
    @PreAuthorize("@ss.hasPermi('waybills:waybill:query')")
    @GetMapping(value = "/{wayBillId}")
    public AjaxResult getInfo(@PathVariable("wayBillId") Long wayBillId)
    {
        return success(tWayBillInfoService.selectTWayBillInfoByWayBillId(wayBillId));
    }

    /**
     * 新增运单信息
     */
    @PreAuthorize("@ss.hasPermi('waybills:waybill:add')")
    @Log(title = "运单信息", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody TWayBillInfo tWayBillInfo)
    {
//        logger.debug("GGG " + "add = " + tWayBillInfo);
        updateMobileAndNumberRelateInfo(tWayBillInfo);
        tWayBillInfo.setCreateBy(getNickName());
        return toAjax(tWayBillInfoService.insertTWayBillInfo(tWayBillInfo));
    }

    /**
     * 修改运单信息
     */
    @PreAuthorize("@ss.hasPermi('waybills:waybill:edit')")
    @Log(title = "运单信息", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody TWayBillInfo tWayBillInfo)
    {
        updateMobileAndNumberRelateInfo(tWayBillInfo);
        tWayBillInfo.setUpdateBy(getNickName());
        return toAjax(tWayBillInfoService.updateTWayBillInfo(tWayBillInfo));
    }

    /**
     * 计算并修改运单信息
     */
    @PreAuthorize("@ss.hasPermi('waybills:waybill:edit')")
    @Log(title = "运单信息", businessType = BusinessType.CALCULATE)
    @PutMapping("/calculate")
    public AjaxResult calculate(@RequestBody TWayBillInfo tWayBillInfo)
    {
        //logger.debug("XXX " + "tWayBillInfo = " + tWayBillInfo);
        tWayBillInfo.setUpdateBy(getNickName());
        //calculateAndUpdateTWayBillInfo(tWayBillInfo);
        return toAjax(tWayBillInfoService.updateTWayBillInfo(calculateAndUpdateTWayBillInfo(tWayBillInfo)));
    }

    /**
     * 删除运单信息
     */
    @PreAuthorize("@ss.hasPermi('waybills:waybill:remove')")
    @Log(title = "运单信息", businessType = BusinessType.DELETE)
	@DeleteMapping("/{wayBillIds}")
    public AjaxResult remove(@PathVariable Long[] wayBillIds)
    {
        return toAjax(tWayBillInfoService.deleteTWayBillInfoByWayBillIds(wayBillIds));
    }

    /**
     * 更新“发货电话”相关信息，
     * 更新“收货电话”相关信息，
     * 更新“车牌号”相关信息
     */
    private void updateMobileAndNumberRelateInfo(TWayBillInfo tWayBillInfo) {
        TSendReceiveInfo tSendReceiveInfo = new TSendReceiveInfo();
        TVehicleDriverInfo tVehicleDriverInfo = new TVehicleDriverInfo();

//        logger.debug("GGG " + "edit = " + tWayBillInfo);
        //更新电话，人，地址，流向，
//        logger.debug("GGG " + "edit tWayBillInfo.getSendGoodsMobile() = " + tWayBillInfo.getSendGoodsMobile());
        /* 发货电话不为空，处理 */
        if(!(tWayBillInfo.getSendGoodsMobile() == null || tWayBillInfo.getSendGoodsMobile().isEmpty())) {
//            logger.debug("GGG " + "edit = " + "tSendReceiveInfo");
            tSendReceiveInfo.setMobile(tWayBillInfo.getSendGoodsMobile());
//        logger.debug("GGG " + "edit = " + tSendReceiveInfo);
            List<TSendReceiveInfo> list = tSendReceiveInfoService.selectTSendReceiveInfoByMobile(tSendReceiveInfo);
//            logger.debug("Send GGG list " + "edit = " + list);
            tSendReceiveInfo.setMobile(tWayBillInfo.getSendGoodsMobile());
            tSendReceiveInfo.setPerson(tWayBillInfo.getSendGoodsPerson());
            tSendReceiveInfo.setAddress(tWayBillInfo.getSendGoodsAddress());
            tSendReceiveInfo.setDirection(tWayBillInfo.getBeginFlowDirection());
            tSendReceiveInfo.setCustomer(tWayBillInfo.getSendGoodsCustomer());

            if (list.isEmpty()) {
                tSendReceiveInfo.setCreateBy(getNickName());
                tSendReceiveInfo.setRemark(null);
                tSendReceiveInfo.setUpdateBy(null);
                tSendReceiveInfo.setUpdateTime(null);
                tSendReceiveInfoService.insertTSendReceiveInfo(tSendReceiveInfo);
//                logger.debug("Send GGG isEmpty " + "edit = " + tSendReceiveInfo);
            } else {
                tSendReceiveInfo.setSendReceiveId(list.get(0).getSendReceiveId());
                tSendReceiveInfo.setUpdateBy(getNickName());
                tSendReceiveInfoService.updateTSendReceiveInfo(tSendReceiveInfo);
//                logger.debug("Send GGG notEmpty " + "edit = " + tSendReceiveInfo);
            }
        } else {
            logger.debug("Send HHH mobile is empty ");
        }
        /* 收货电话不为空，处理 */
        if(!(tWayBillInfo.getReceiveGoodsMobile() == null || tWayBillInfo.getReceiveGoodsMobile().isEmpty())) {
            tSendReceiveInfo.setMobile(tWayBillInfo.getReceiveGoodsMobile());
//        logger.debug("HHH " + "edit = " + tSendReceiveInfo);
            List<TSendReceiveInfo> list = tSendReceiveInfoService.selectTSendReceiveInfoByMobile(tSendReceiveInfo);
//            logger.debug("Receive HHH list " + "edit = " + list);
            tSendReceiveInfo.setMobile(tWayBillInfo.getReceiveGoodsMobile());
            tSendReceiveInfo.setPerson(tWayBillInfo.getReceiveGoodsPerson());
            tSendReceiveInfo.setAddress(tWayBillInfo.getReceiveGoodsAddress());
            tSendReceiveInfo.setDirection(tWayBillInfo.getEndFlowDirection());
            tSendReceiveInfo.setCustomer(tWayBillInfo.getReceiveGoodsCustomer());
            tSendReceiveInfo.setRemark(tWayBillInfo.getReceiveGoodsRemark());

            if (list.isEmpty()) {
                tSendReceiveInfo.setCreateBy(getNickName());
                tSendReceiveInfo.setUpdateBy(null);
                tSendReceiveInfo.setUpdateTime(null);
                tSendReceiveInfoService.insertTSendReceiveInfo(tSendReceiveInfo);
//                logger.debug("Receive HHH isEmpty " + "edit = " + tSendReceiveInfo);
            } else {
                tSendReceiveInfo.setSendReceiveId(list.get(0).getSendReceiveId());
                tSendReceiveInfo.setUpdateBy(getNickName());
                tSendReceiveInfoService.updateTSendReceiveInfo(tSendReceiveInfo);
//                logger.debug("Receive HHH notEmpty " + "edit = " + tSendReceiveInfo);
            }
        } else {
            logger.debug("Receive HHH mobile is empty ");
        }
        //更新车牌，司机，电话
        if(!(tWayBillInfo.getVehicleLicenseNumber() == null || tWayBillInfo.getVehicleLicenseNumber().isEmpty())) {
//            logger.debug("HHH " + "edit = " + tVehicleDriverInfo);
            tVehicleDriverInfo.setVehicleLicenseNumber(tWayBillInfo.getVehicleLicenseNumber());
            List<TVehicleDriverInfo> list = tVehicleDriverInfoService.selectTVehicleDriverInfoByNumber(tVehicleDriverInfo);
            tVehicleDriverInfo.setDriverName(tWayBillInfo.getDriverName());
            tVehicleDriverInfo.setContactMobile(tWayBillInfo.getContactMobile());
            if (list.isEmpty()) {
                tVehicleDriverInfo.setCreateBy(getNickName());
                tVehicleDriverInfo.setUpdateBy(null);
//                tVehicleDriverInfo.setUpdateBy(null);
                tVehicleDriverInfoService.insertTVehicleDriverInfo(tVehicleDriverInfo);
            } else {
                tVehicleDriverInfo.setVehicleDriverId(list.get(0).getVehicleDriverId());
                tVehicleDriverInfo.setUpdateBy(getNickName());
                tVehicleDriverInfoService.updateTVehicleDriverInfo(tVehicleDriverInfo);
            }
        } else {
            logger.debug("Vehicle HHH Number is empty ");
        }
//
    }

    private TWayBillInfo calculateAndUpdateTWayBillInfo(TWayBillInfo tWayBillInfo) {
        logger.debug("XXX " + "tWayBillInfo = " + tWayBillInfo);
        double totalWeight = tGoodsInfoService.calculateTotalWeightByWayBillNumber(tWayBillInfo.getWayBillNumber());
        logger.debug("XXX " + "totalWeight = " + totalWeight);
        tWayBillInfo.setFreightWeight(totalWeight);
        return tWayBillInfo;
    }
}
